<template>
  <el-dialog
    center
    v-if="isShow"
    v-dialogDrag
    :title="title"
    :width="dialogWidth"
    :before-close="close"
    :visible.sync="isShow"
    class="dialog-permit-tree"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      class="mt20 overflow pl15 pr15"
    >
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item label="当前部门：" :label-width="labelWidth">{{
            form.deptName
          }}</el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            label="岗位名称："
            prop="jobName"
            :label-width="labelWidth"
          >
            <el-input v-model="form.jobName" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            label="岗位属性："
            prop="characterType"
            :label-width="labelWidth"
          >
            <el-select v-model="form.characterType">
              <el-option label="管理者" value="1"></el-option>
              <el-option label="执行者" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="editJobDialog">
        <el-col :span="24" class="mb15">
          <div></div>
          <el-tabs type="border-card" v-loading.lock="fullscreenLoading">
            <el-tab-pane label="App">
              <el-checkbox
                label="1"
                class="pl20 mb20"
                v-model="checkedAllOfApp"
                @change="handleCheckedAll('action1ref', checkedAllOfApp)"
                >勾选/取消所有业务权限</el-checkbox
              >
              <el-checkbox
                label="1"
                class="pl20 mb20"
                v-model="expendAllOfApp"
                @change="handleExpendAll('action1ref', expendAllOfApp)"
                >全部展开/全部收起</el-checkbox
              >
              <div v-for="(action, index) in actions1" :key="index">
                <div class="action-title ml10 pl10 pb10 overflow">
                  <span class="fl">{{ action.name }}</span>
                  <div class="fr mr20">
                    <el-checkbox
                      v-model="checkedAllOfAppItem[index]"
                      @change="
                        handleCheckedAllOfItem(
                          'action1ref',
                          checkedAllOfAppItem[index],
                          index
                        )
                      "
                      >全选</el-checkbox
                    >
                  </div>
                </div>
                <div class="mt15 pl20">
                  <el-form-item prop="actions">
                    <el-tree
                      show-checkbox
                      node-key="id"
                      ref="action1ref"
                      :props="defaultProps"
                      :data="action.menuChildList"
                      :render-after-expand="false"
                      :expand-on-click-node="false"
                      @check-change="handleChangeTreeCheck"
                      :default-checked-keys="checkedMenuIds1"
                    ></el-tree>
                  </el-form-item>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="后台">
              <el-checkbox
                label="1"
                class="pl20"
                v-model="checkedAll"
                @change="handleCheckedAll('action2ref', checkedAll)"
                >勾选/取消所有业务权限</el-checkbox
              >
              <el-checkbox
                label="1"
                class="pl20 mb20"
                v-model="expendAll"
                @change="handleExpendAll('action2ref', expendAll)"
                >全部展开/全部收起</el-checkbox
              >
              <div
                class="mt20"
                v-for="(action, index) in actions2"
                :key="index"
              >
                <div class="action-title ml10 pl10 pb10 overflow">
                  <span class="fl">{{ action.name }}</span>
                  <div class="fr mr20">
                    <el-checkbox
                      v-model="checkedAllOfItem[index]"
                      @change="
                        handleCheckedAllOfItem(
                          'action2ref',
                          checkedAllOfItem[index],
                          index
                        )
                      "
                      >全选</el-checkbox
                    >
                  </div>
                </div>
                <div class="mt15 pl20">
                  <el-form-item prop="actions">
                    <el-tree
                      node-key="id"
                      show-checkbox
                      ref="action2ref"
                      :props="defaultProps"
                      :data="action.menuChildList"
                      :render-after-expand="false"
                      :expand-on-click-node="false"
                      v-if="action.menuChildList.length"
                      @check-change="handleChangeTreeCheck"
                      :default-checked-keys="checkedMenuIds2"
                    ></el-tree>
                  </el-form-item>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer align-center tiling inline-block"
      v-loading="loading"
    >
      <el-button @click="close">取 消</el-button>
      <el-button class="theme-btn" @click="handleConfirm">提 交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import "@/utils/drag.js";
import { vName } from "@/utils/verification.js";
import { getActions, editJob, editAction, addJob } from "@/apis/user";

export default {
  name: "Job_dialog",
  data() {
    return {
      form: {
        jobName: "",
        actions: [],
        deptName: "",
        characterType: ""
      },
      actions1: [],
      actions2: [],
      activeNames: "",
      expendAll: false,
      checkedAll: false,
      labelWidth: "95px",
      checkedMenuIds1: [],
      checkedMenuIds2: [],
      checkedAllOfItem: [],
      expendAllOfApp: false,
      checkedAllOfApp: false,
      checkedAllOfAppItem: [],
      fullscreenLoading: false,
      defaultProps: {
        children: "menuChildList",
        label: "name"
      },
      rules: {
        jobName: {
          validator: vName(2, 8, "请输入岗位名称"),
          trigger: "blur"
        },
        characterType: {
          required: true,
          message: "请选择岗位属性",
          trigger: "blur"
        }
      }
    };
  },
  computed: {
    isShow() {
      return this.addJobDialog || this.editJobDialog;
    },
    dialogWidth() {
      return this.editJobDialog ? "940px" : "640px";
    },
    permitMenu() {
      return JSON.parse(sessionStorage.getItem("permitMenu"));
    }
  },
  watch: {
    addJobDialog() {
      this.form = {
        actions: [],
        deptId: this.jobForm.deptId,
        deptName: this.jobForm.deptName
      };
    },
    editJobDialog() {
      this.form = {
        actions: [],
        jobId: this.jobForm.jobId,
        deptId: this.jobForm.deptId,
        jobName: this.jobForm.jobName,
        deptName: this.jobForm.deptName,
        characterType: String(this.jobForm.characterType)
      };

      this.openFullScreen();
      this.getActionList();
    }
  },
  methods: {
    openFullScreen() {
      this.fullscreenLoading = true;
      setTimeout(() => {
        this.fullscreenLoading = false;
      }, 1000);
    },
    handleChangeTreeCheck(data, nodeChecked) {
      if (data.menuChildList) return;

      data.permission = nodeChecked ? 1 : 0;
      // nodeChecked // 自身是否被选中
      // childChecked // 子类中是否有被选中
      // 1表示全选中，2表示不全选中，0表示未选中
    },
    handleCheckedAll(ref, checkedAll) {
      const actionrefs = this.$refs[ref];

      actionrefs.forEach((action, idx) => {
        action.setChecked(action.root, checkedAll, true);
      });
    },
    handleCheckedAllOfItem(ref, checkedAll, index) {
      const action = this.$refs[ref][index];
      action.setChecked(action.root, checkedAll, true);
    },
    operationActions(actions) {
      const copeActions = JSON.parse(JSON.stringify(actions)); // 对象拷贝

      const operationAction = action => {
        const childAction = action.menuChildList;
        if (!childAction) return;

        const sonPerms = childAction.filter(item => {
          // 获取子类选中状态
          if (item.menuChildList) {
            // 子类还有子类时递归
            operationAction(item);
          }

          return item.permission === 1;
        });

        const sonPermsLength = sonPerms.length;
        if (sonPermsLength === 0) {
          // 子类无选中表示未选
          action.permission = 0;
        } else if (sonPermsLength === childAction.length) {
          // 子类选中的数量等于父类表示全选
          action.permission = 1;
        } else {
          // 子类有选中且子类选中的数量不等于父类表示半选中
          action.permission = 2;
        }
      };

      copeActions.forEach(action => operationAction(action));

      return copeActions;
    },
    async getActionList() {
      const res1 = await getActions({
        appId: 2,
        jobId: this.form.jobId
      });
      this.actions1 = [...res1.object.menuNodes];
      this.checkedMenuIds1 = [...res1.object.checkedMenuIds];

      const res2 = await getActions({
        appId: 1,
        jobId: this.form.jobId
      });

      this.actions2 = [...res2.object.menuNodes];
      this.checkedMenuIds2 = [...res2.object.checkedMenuIds];
    },
    handleConfirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.editJobDialog ? this.editJob() : this.addJob();
        }
      });
    },
    editJob() {
      const params = {
        jobId: this.form.jobId,
        jobName: this.form.jobName,
        characterType: this.form.characterType,
        menu: [
          ...this.operationActions(this.actions1),
          ...this.operationActions(this.actions2)
        ],
       };

      this.$store.dispatch("load/setLoading", true);
      // editAction(params).then(res => {
      //   if (res && res.code === "200") {
      //     this.$emit("update");
      //     this.close();
      //     this.$notify({
      //       title: res.msg,
      //       type: "success"
      //     });
      //   }
      // });
      this.$emit("update");
      this.close();
      this.$notify({
        title: "操作成功!",
        type: "success"
      });
    },
    handleExpendAll(ref, expendAll) {
      const actionrefs = this.$refs[ref];
      actionrefs.forEach((action, idx) => {
        action.root.childNodes.forEach(item => {
          item.expanded = expendAll;
        });
      });
    },
    addJob() {
      const params = {
        name: this.form.jobName,
        departmentId: this.form.deptId,
        characterType: this.form.characterType
      };

      this.$store.dispatch("load/setLoading", true);
      // addJob(params).then(res => {
      //   if (res && res.code === "200") {
      //     this.$emit("update");
      //     this.close();
      //     this.$notify({
      //       title: res.msg,
      //       type: "success"
      //     });
      //   }
      // });
      this.$emit("update");
      this.close();
      this.$notify({
        title: "操作成功!",
        type: "success"
      });
    },
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        deptName: "",
        jobName: "",
        actions: [],
        characterType: ""
      };
    }
  },
  props: ["addJobDialog", "editJobDialog", "title", "jobForm", "loading"]
};
</script>

<style scoped></style>
